import {createRouter, createWebHistory} from 'vue-router'
import {useUserStore} from '@/stores/user'
import {Message} from '@arco-design/web-vue'

const modules = import.meta.glob('../views/**/*.vue')
// 路由模块化配置
const staticRoutes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/common/LoginPage.vue'),
        meta: {
            title: '统一认证平台', ignoreAuth: true
        }
    }, // 主框架路由
    {
        path: '/',
        name: 'Layout',
        component: () => import('@/views/Main.vue'),
        redirect: '/dashboard',
        children: [{
            path: '/dashboard',
            name: 'Dashboard', component: () => import('@/views/common/Analysis.vue'),
            meta: {
                title: '仪表盘', icon: 'icon-dashboard'
            }
        },
            {
                path: '/:pathMatch(.*)*',
                name: 'NotFound',
                component: () => import('@/views/common/404.vue'),
                meta: {hidden: true}
            }, {
                path: '/401',
                name: 'NoPermission',
                component: () => import('@/views/common/401.vue'),
                meta: {
                    hidden: true
                }
            }]
    }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.VITE_BASE_URL),
    routes: staticRoutes,
    scrollBehavior(to, from, savedPosition) {
        return savedPosition || {top: 0}
    }
})

/** 路由守卫 */
router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()
    try {
        await userStore.$hydrate(); // 等待真正的数据加载
    } catch (error) {
        console.error('持久化数据加载失败:', error);
        return next('/error');
    }
    const {tenantId} = userStore
    // 租户ID校验
    if (!tenantId && to.meta.tenantAware) {
        console.log('请先选择租户')
        Message.error('请先选择租户')
        return next('/login')
    }

    // 页面标题设置
    document.title = `${to.meta.title} - ${import.meta.env.VITE_APP_TITLE}`

    // 登录状态检查
    if (!to.meta.ignoreAuth) {
        if (!userStore.token) {
            return next({path: '/login', query: {redirect: to.fullPath}})
        }
        // 修改动态路由加载部分
        if (!userStore.asyncRoutesAdded || !router.hasRoute('系统管理')) {
            // 4. 转换路由配置
            const dynamicRoutes = filterAsyncRoutes(userStore.menuTree)
            // 5. 动态添加
            addDynamicRoutes(dynamicRoutes)
            userStore.asyncRoutesAdded = true
            return next({path: to.fullPath, replace: true})
        }
    }

    // 权限校验
    if (to.meta.permission) {
        const hasPermission = userStore.permissions?.some(p => to.meta.permission.includes(p))
        if (!hasPermission) return next('/401')
    }

    next()
})

/**
 * 将菜单树转换为 Vue Router 配置（你的核心逻辑保留）
 * @param {Array} menuTree 后端返回的菜单树
 * @returns {Array} 符合 Vue Router 的路由配置
 */
function filterAsyncRoutes(menuTree) {

    const routes = []

    const generateRoute = (node) => {
        const route = {
            path: node.menu.path,
            name: node.menu.menuName,
            component: node.menu.menuType === 'MENU' ? modules[`../views${node.menu.path}.vue`] : null,
            meta: {
                title: node.menu.menuName, icon: node.menu.icon, requiresAuth: !node.menu.hidden
            },
        };

        if (node.children?.length) {
            route.children = node.children.map(generateRoute);
        }

        return route;
    };

    menuTree.forEach(node => {
        routes.push(generateRoute(node))
    })


    return routes;
}

/**
 * 动态添加路由核心方法（新增）
 * @param {Array} filteredRoutes 经过 filterAsyncRoutes 处理的路由
 */
function addDynamicRoutes(filteredRoutes) {
    filteredRoutes.forEach(route => {
        if (!router.hasRoute(route.name)) {
            // 关键逻辑：嵌套路由需挂载到布局路由下
            router.addRoute('Layout', route) // 挂载到布局路由
        }
    })
    // 调试：打印所有路由
    console.log('当前路由表:', router.getRoutes())
}

// 网络错误处理
router.onError((error) => {
    if (/ChunkLoadError|Loading chunk/.test(error.message)) {
        window.location.reload()
    }
})

export default router